<?php

namespace app\index\controller;

use WxPay;

/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 2018/11/14
 * Time: 9:33
 */
class Notify extends Common
{
    /**
     * 微信支付回调
     */
    public function wxPayCallBackUrl()
    {
        // 获取返回的post数据包
//        $post_str = $GLOBALS["HTTP_RAW_POST_DATA"];
        $post_str = file_get_contents('php://input'); //替代上面的代码，服务器无法通过上面的方法获取到内容
        if (!empty($post_str)) {
            libxml_disable_entity_loader(true);
            $post_obj = (array)simplexml_load_string($post_str, 'SimpleXMLElement', LIBXML_NOCDATA);
            $isSign = $this->isWechatSign($post_obj);
            if ($post_obj['result_code'] == 'SUCCESS' && $isSign) {
                //订单号
                $order_no = $post_obj['out_trade_no'];
                //
                $open_id = $post_obj['openid'];
                //     Db::table('my_errs')->insert(['content'=>json_encode($order_wx)]);
                //更新订单数据
                $this->updateOrderIsPay($order_no);
                $order_amount = (int)$post_obj['total_fee'] / 100;

                //发送客服消息
//                    $this->sendPayOkMessage($order_no, $order_amount, $open_id);
                //保存支付记录
                $save_data = [
                    'order_no' => $order_no,
                    'pay_type' => 'WxPay',
                    'openid' => $open_id,
                    'total_fee' => $post_obj['total_fee'],
                    'trade_type' => $post_obj['trade_type'],        //JSAPI、NATIVE、APP
                    'bank_type' => $post_obj['bank_type'],
                    'result_code' => $post_obj['result_code'],
                    'transaction_id' => $post_obj['transaction_id'],
                    'time_end' => $post_obj['time_end'],
                ];
                //  Db::table('my_errs')->insert(['content'=>json_encode($save_data)]);
//                    Loader::model('base/OrdersStatus')->editData($save_data);
                $this->echoCallBack(true);

            } else {
                $this->echoCallBack();
            }
        } else {
            $this->echoCallBack();
        }

    }

    /**
     * 验证微信返回签名的合法性
     *
     * @param array smap
     * @param String apiKey 微信支付key
     * @return
     */
    private function isWechatSign($data)
    {
        $oldSign = $data["sign"];
        $type = false;
        unset($data["sign"]);
        $WxPay = new WxPay();
        $sign = $WxPay->getSign($data);

        if ($sign == $oldSign) {
            $type = true;
        }
        return $type;
    }

    /**
     * 更新订单状态
     * @param string $order_no 订单号
     * @param string $pay_type 支付类型
     */
    protected function updateOrderIsPay($order_no, $pay_type = 'wx')
    {

        $update_data = [
            'pay_status' => 1,
            'order_status' => 1,
            'pay_time' => time()
        ];
        db("order")->where("order_sn", $order_no)->update($update_data);
    }

    /**
     * 发送微信服务号消息（未完善） 2018-11-14
     * @param $order_no
     * @param $order_amount
     * @param $open_id
     * @return bool
     */
    protected function sendPayOkMessage($order_no, $order_amount, $open_id)
    {

        $add_message = [
            'title' => '订单支付成功通知',
            'template_id' => 'NlBWOshEjRxoRtpodi-_Tt2XVfe5TNh-uAbDXkkJ4vw',
            'url' => $this->request->domain() . '/index/WC_html_1/mainContainer.html#order/order_orderInfo.html||orderId=' . $order_no,
            'data' => [
                'first' => ['value' => '您好,您的订单已支付成功，我们会尽快为您发货(callBack)',],
                'keyword1' => ['value' => $order_no,],
                'keyword2' => ['value' => $order_amount . '元',],
                'remark' => ['value' => '我们已经收到你的货款请耐心等待收货。',],
            ],
        ];
        $reg = controller('base/WxApi')->sendTemplateMessage($add_message, $open_id);
        return $reg ? true : false;

    }

    /**
     * 通知微信结果
     */
    protected function echoCallBack($status = false)
    {
        if (!$status) {
            $result = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[未接收到post数据]]></return_msg></xml>";
        } else {
            $result = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
        }
        echo $result;
    }

}